package com.hqyj.finance.server.bill.financebill.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.hqyj.finance.server.bill.financebill.service.QiniuService;
import com.hqyj.finance.server.bill.financebill.utils.FileUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.UUID;

@Service
public class QiniuServiceImpl implements QiniuService {

    private static final Logger logger = LoggerFactory.getLogger(QiniuService.class);

    @Value("${qiniu.access_key}")
    // 设置好账号的ACCESS_KEY和SECRET_KEY
    private String ACCESS_KEY="";
    @Value("${qiniu.secret_key}")
    private String SECRET_KEY="";
    // 要上传的空间
    @Value("${qiniu.bucket_name}")
    private String bucketname="";

    // 测试域名，只有30天有效期
    @Value("${qiniu.domain_name}")
    private String QINIU_IMAGE_DOMAIN;

    // 密钥配置
    Auth auth ;
    // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
    Configuration cfg;
    // ...其他参数参考类注释
    UploadManager uploadManager;

    @PostConstruct
    public void init() {
        auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        cfg = new Configuration(Zone.autoZone()); //区域让七牛云自动去判断。
        uploadManager = new UploadManager(cfg);
    }

    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    public String saveImage(MultipartFile file) throws IOException {
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
            if (!FileUtil.isFileAllowed(fileExt)) {
                return null;
            }

            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            //resp.code ===200
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }

    @Override
    public String saveExcelFile(File file) throws IOException{
        try{
            InputStream inputStream = Files.newInputStream(file.toPath());
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes,0,bytes.length);
            // 调用put方法上传
            //Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            Response res = uploadManager.put(bytes, file.getName(), getUpToken());
            // 打印返回的信息
            //resp.code ===200
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                return QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("七牛异常:" + res.bodyString());
                return null;
            }
        }catch (QiniuException e){
            // 请求失败时打印的异常的信息
            logger.error("七牛异常:" + e.getMessage());
            return null;
        }
    }
}
